/*
Java board game library.
Copyright (C) 2011  Deepesh Garg

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

package d.g.boardgames.chess;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import d.g.boardgames.Cell;
import d.g.boardgames.chess.ChessCellState.PieceType;
import d.g.boardgames.chess.ChessMove.Casteling;
public class CoordinateMoveParser implements ChessMoveParser {

	public String createMoveString(ChessBoard board, ChessMove move) {
		
		return null;
	}

	public ChessMove parseMoveString(ChessBoard board, String moveString) {
		moveString = moveString.replaceFirst("-", "");
		moveString = moveString.replaceFirst("x", "");
		moveString = moveString.replaceFirst("X", "");
		moveString = moveString.replaceFirst("=", "");
		if (moveString.equalsIgnoreCase("oo")) {
			return new ChessMove (Casteling.KING_SIDE);
		}
		if (moveString.equalsIgnoreCase("ooo")) {
			return new ChessMove (Casteling.QUEEN_SIDE);
		}
		if (moveString.length() < 4) {
			return null;
		}
		Pattern pattern = Pattern.compile("[a-h][1-8][a-h][1-8]");
		Matcher matcher = pattern.matcher(moveString);
		if (!matcher.find()) {
			return null;
		}
		moveString = matcher.group();
		Cell fromCell = AlgebricNotationHelper.getCell(moveString.substring(0, 2));
		Cell toCell = AlgebricNotationHelper.getCell(moveString.substring(2, 4));
		
		ChessCellState fromCellState = board.getCellState(fromCell);
		if (fromCellState != null) {
			if (fromCellState.pieceType == PieceType.KING) {
				if (fromCell.getCol() == 4 && toCell.getCol() == 6) {
					return new ChessMove(Casteling.KING_SIDE);
				}
				if (fromCell.getCol() == 4 && toCell.getCol() == 2) {
					return new ChessMove(Casteling.QUEEN_SIDE);
				}
			}
		}
		
		ChessMove chessMove = new ChessMove (fromCell, toCell);
		if (moveString.length() == 5 && fromCellState.pieceType == PieceType.PAWN &&
				(toCell.getRow() == 0 || toCell.getRow() == 7)) {	
			chessMove.setPawnPromotion(AlgebricNotationHelper.getPieceType(moveString.substring(4, 5)));
		}
		return chessMove;
	}

}
